const express = require('express')
const pool = require('../pool.js')
// 创建路由器对象
const router = express.Router()
module.exports = router

// 用户注册接口
router.post('/reg', (req, res) => {
  // 验证手机号
  if (!/^1[3-9]\d{9}$/.test(req.body.phone)) {
    console.log('手机号错误')
    return
  }
  let uname = req.body.uname
  let pwd = req.body.pwd
  let phone = req.body.phone
  // 验证用户名唯一性
  let sql = 'select count(uid) as count from e_user where uname=?'
  pool.query(sql, [uname], (err, result) => {
    if (err) throw err
    let count = result[0].count
    if (count == 0) {
      sql = 'insert into e_user(uname,pwd,phone) values(?,?,?)'
      pool.query(sql, [uname, pwd, phone], (err, result) => {
        if (err) {
          throw err
        }
        console.log(result)
        res.send({ code: 200, msg: '注册成功' })
      })
    } else {
      res.send({ code: 201, message: 'user exists' });
    }
  })
})


// 用户登录接口
router.post('/login', (req, res) => {
  let uname = req.body.uname
  let pwd = req.body.pwd
  let sql = 'select * from e_user where uname=? and pwd=?'
  pool.query(sql, [uname,pwd],(err, results) => {
    if (err) throw err;
    if (results.length == 0) { //登录失败
      res.send({ message: 'login failed', code: 201 });
    } else {                 //登录成功
      res.send({ message: 'ok', code: 200, result: results[0] });
    }
  })
})

